
<template>
  <div class="app-container">
    <div class="app-permission-container flex-between mb8">
      <span class="page-list-title">设置商户类型</span>
      <div class="action-content">
        <el-button v-hasPermi="['admin:setting:add']" type="primary" size="mini" @click="showDialog('setting', 'add')"
        >新增</el-button>
      </div>
    </div>
    <div class="app-table-container">
      <el-table
        v-loading="boo.loading"
        :data="list" border header-row-class-name="app-table-list"
      >
        <el-table-column
          label="商户类型"
          align="center"
          key="shopType"
          prop="shopType"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="{row}">
            {{ row['shopType'] | numToStr(dictsList, 'shopType') }}
          </template>
        </el-table-column>
        <el-table-column
          label="版本类型"
          align="center"
          key="versionType"
          prop="versionType"
          :show-overflow-tooltip="true"
          >
          <template slot-scope="{row}">
            {{ row['versionType'] | numToStr(dictsList, 'versionType') }}
          </template>
        </el-table-column>
        <el-table-column
          label="版本名称"
          align="center"
          key="versionName"
          prop="versionName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="活动类型"
          align="center"
          key="activityTypes"
          prop="activityTypes"
          :show-overflow-tooltip="true"> 
        </el-table-column>
        <el-table-column
          label="描述"
          align="center"
          key="remarks"
          prop="remarks"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="服务年费（元）"
          align="center"
          key="yearFee"
          prop="yearFee"
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="text" v-hasPermi="['admin:setting:edit']"
              icon="el-icon-edit" :loading="row.isEdit"
              @click="showDialog('setting', 'edit', row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text" v-hasPermi="['admin:setting:remove']"
              icon="el-icon-delete"
              @click="deleteRow(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="other.total > 0"
        :total="other.total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 设置弹窗 -->
    <dialog-normal
      ref="dialog-setting"
      :dialog-prop="{
        title: dialogSetting.title,
        height: '45vh',
        width: '60%',
        submit: '确定',
        close: '取消'
      }"
      @normal-submit="submitDialog('setting', dialogSetting.currentItem)"
    >
      <template #dialog-content v-if="$refs[`dialog-setting`] && $refs[`dialog-setting`].showDialog" >
        <el-form
          class="form-content"
          ref="setting-form" label-position="left"
          :model="dialogSetting.currentItem"
          label-width="120px">
          <div class="form-title">基本信息</div>
          <el-form-item class="form-content-item"
            label="商户类型：" prop="shopType"
            :rules="{ required: true, message: `商户类型不能为空`, trigger: 'change'}">
            <div class="form-val flex-normal">
              <el-select v-model="dialogSetting.currentItem['shopType']" placeholder="请选择商户类型">
                <el-option
                  v-for="item in getDictItem('shopType')"
                  :key="item.dictValue" filterable
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
            label="版本类型：" prop="versionType"
            :rules="{ required: true, message: `版本类型不能为空`, trigger: 'change'}">
            <div class="form-val flex-normal">
              <el-select v-model="dialogSetting.currentItem['versionType']" placeholder="请选择版本类型">
                <el-option
                  v-for="item in getDictItem('versionType')"
                  :key="item.dictValue" filterable
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
            label="版本名称：" prop="versionName"
            :rules="[
              { required: true, message: `版本名称不能为空`, trigger: 'input',}
            ]">
            <div class="form-val flex-normal">
              <el-input v-model="dialogSetting.currentItem['versionName']" placeholder="请输入版本名称"></el-input>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
            label="服务年费：" prop="yearFee"
            :rules="[
              { required: true, message: `服务年费不能为空`, trigger: 'input',},
              { validator: validateMoney, trigger: 'blur'}
            ]">
            <div class="form-val flex-normal">
              <el-input v-model="dialogSetting.currentItem['yearFee']" placeholder="请输入服务年费"></el-input>
              <span class="val-unit">元/年</span>
            </div>
          </el-form-item>
          <el-form-item v-if="dialogSetting.currentItem['versionType'] == 2" class="form-content-item"
            label="店铺费用：" prop="shopFee"
            :rules="[
              { required: true, message: `店铺费用不能为空`, trigger: 'input',},
              { validator: validateMoney, trigger: 'blur'}
            ]">
            <div class="form-val flex-normal">
              <el-input v-model="dialogSetting.currentItem['shopFee']" placeholder="请输入店铺费用"></el-input>
              <span class="val-unit">元/个</span>
            </div>
          </el-form-item>
          <el-form-item v-if="dialogSetting.currentItem['versionType'] == 2" class="form-content-item"
            label="默认店铺：" prop="defaultShop"
            :rules="[
              { required: true, message: `店铺数目不能为空`, trigger: 'input',},
              { validator: validateNum, trigger: 'blur'}
            ]">
            <div class="form-val flex-normal">
              <el-input v-model="dialogSetting.currentItem['defaultShop']" placeholder="请输入店铺数目"></el-input>
              <span class="val-unit">个</span>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
            label="描述：" prop="remarks"
            :rules="{ required: false, message: `描述不能为空`, trigger: 'blur'}">
            <div class="form-val flex-normal">
              <el-input v-model="dialogSetting.currentItem['remarks']" placeholder="请输入描述"></el-input>
            </div>
          </el-form-item>
          <div class="form-title">活动类型</div>
          <active-tree :list="activeTypeList" v-model="dialogSetting.currentItem['shopAndActivityTypes']"/>
        </el-form>
      </template>
    </dialog-normal>
  </div>
</template>
  
<script>
import {
  getList, addItem, editItem, getDetail, delItem
} from "@/api/system/settingList";
import {getActiveTypeDict} from '@/api/common/index.js'
import {isDecimal} from '@/utils/tools.js'
export default {
  name: "List",
  components: {
    "dialog-normal": () => import("@/rhComponents/dialog/normal-dialog"),
    "active-tree": () => import("./temp/active-tree.vue"),
  },
  filters: {
    numToStr(num, list, type){
      let index = list.findIndex(item => item.name == type)
      if(index == -1) return '未定义参数'
      let idx = list[index].child.findIndex(i => i.dictValue == num)
      if(idx == -1) return '---'
      return list[index].child[idx].dictLabel
    }
  },
  data() {
    return {
      boo: {
        loading: false, // 遮罩层
        multiple: true, // 非多个禁用
        showSearch: true, // 显示搜索条件
      }, 
      other: {
        ids: [], // 选中数组
        total: 0, //总条数
      },
      activeTypeList: [],
      dictsList: [
        { label: "版本类型", name: "versionType", deptType: "versionType", child: [] },
        { label: "商户类型", name: "shopType", deptType: "shopType", child: [] },
        { label: "活动类型", name: "activityType", deptType: "activityType", child: [] }
      ],
      // 列信息
      columns: [
        { key: 0, label: `地块编号`, visible: false },
        { key: 1, label: `地块名称`, visible: true },
        { key: 2, label: `地块类型`, visible: true },
        { key: 3, label: `负责人`, visible: true },
        { key: 4, label: `面积（亩）`, visible: true },
        { key: 5, label: `当前作物`, visible: true },
        { key: 6, label: `地块位置`, visible: true },
        { key: 7, label: `设备数量`, visible: true },
        { key: 8, label: `所属企业`, visible: true },
      ],
      deviceList: [], //设备列表
      // 地块列表
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      dialogSetting: {
        title: '',
        currentItem: {}
      }
    };
  },
  mounted(){
    let _self = this
    _self.initGetDicts().then(res => {
      _self.queryActiveTypeList()
      _self.getList()
    })
  },
  methods: {
    getDictItem(name){
      let item = this.dictsList.find(i => i.deptType == name)
      return item.child
    },
    validateNum: (rule, value, callback) => {
      let reg = /^\d+$/
      if (!reg.test(value)) {
        callback(new Error('请输入正确的整数'));
      } else {
        callback();
      }
    },
    validateMoney: (rule, value, callback) => {
      if (!isDecimal(`${value}`)) {
        callback(new Error('请输入正确的金额'));
      } else {
        callback();
      }
    },
    /** 查询用户列表 */
    queryActiveTypeList() {
      getActiveTypeDict(this.queryParams)
        .then((res) => {
          this.activeTypeList = (res.data || []).filter(i => i.id != 1)
        })
        .catch(() => {});
    },
    /** 查询用户列表 */
    getList() {
      this.boo.loading = true;
      getList(this.queryParams)
        .then((response) => {
          this.list = response.rows;
          this.other.total = response.total;
          this.boo.loading = false;
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    deleteRow(row) {
      let id = row.id
      this.$modal
        .confirm('是否确认删除？')
        .then(function () {
          return delItem(id);
        })
        .then(() => {
          this.queryParams.pageNum = 1
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 事件集合 -- 转发
    actionsMaps(ref, acion, row){
      let _self = this
      let actionsMap = () => {
        return new Map([
          [{ref: 'setting', acion: 'add:show'}, ()=>{
            _self.dialogSetting.title = '新增商户类型'
            _self.dialogSetting.currentItem = {
              shopAndActivityTypes: [],
              versionType: _self.getDictItem('versionType')[0].dictValue,
              shopType: _self.getDictItem('shopType')[0].dictValue
            }
            _self.$nextTick(() => {
              _self.$refs[`dialog-${ref}`].showDialog = true
            })
          }],
          [{ref: 'setting', acion: 'edit:show'}, ()=>{
            _self.dialogSetting.title = '编辑商户类型'
            _self.$set(row, 'isEdit', true)
            getDetail(row.id).then(res => {
              _self.dialogSetting.currentItem = res.data
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].showDialog = true
              })
            }).finally(() => _self.$set(row, 'isEdit', false))
            
          }],
          [{ref: 'setting', acion: 'submit'}, ()=>{
            let params = row
            let {shopAndActivityTypes = []} = params, msg = ''
            if(!shopAndActivityTypes.length){
              _self.$message.error('至少选择一个活动类型')
              return _self.$refs[`dialog-${ref}`].loading = false;
            }
            shopAndActivityTypes.forEach(i => {
              if(!isDecimal(`${i.serveFee}`) || !isDecimal(`${i.commission}`)){
                msg = '请输入正确的金额'
              }else {
                i.serveFee = parseFloat(i.serveFee)
                i.commission = parseFloat(i.commission)
              }
            })
            if(msg != ''){
              _self.$message.error(msg)
              return _self.$refs[`dialog-${ref}`].loading = false;
            }
            let success = (res, msg) => {
              _self.$message.success(msg)
              _self.getList()
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].showDialog = false
              })
            }
            if(params.id){
              editItem(params).then(res => {
                success(res, '修改成功')
              }).finally(() => {
                _self.$refs[`dialog-${ref}`].loading = false;
              })
            }else {
              addItem(params).then(res => {
                _self.queryParams.pageNum = 1
                success(res, '添加成功')
              }).finally(() => {
                _self.$refs[`dialog-${ref}`].loading = false;
              })
            } 
          }]
        ])
      }
      let actions = [...actionsMap()].filter(([key,value])=>(key.ref == ref && key.acion == acion))
      actions.forEach(([key,value])=>value.call(this))
    },
    showDialog(ref, type, row) {
      let _self = this;
      if (_self.$refs[`${ref}-form`]) {
        this.resetForm(`${ref}-form`);
      }
      _self.$nextTick(() => {
        _self.actionsMaps(ref, `${type}:show`, row)
      })
    },
    submitDialog(ref, row) {
      let _self = this;
      if(this.$refs[`${ref}-form`]){
        this.$refs[`${ref}-form`].validate((valid) => {
          if (valid) {
            _self.$refs[`dialog-${ref}`].loading = true
            _self.actionsMaps(ref, `submit`, row)
          } else {
            _self.$refs[`dialog-${ref}`].loading = false;
            return false;
          }
        });
      }else{
        _self.$refs[`dialog-${ref}`].loading = true
        _self.actionsMaps(ref, `submit`, row)
      }
    },
  }
};
</script>
<style scoped lang="scss">
  .form-content{
    .form-title{
      margin-bottom: vh(20);
      line-height: vh(34);
      font-size: vh(13);
      color: #0003AA;
    }
    .form-val {
      width: vw(360);
      flex-wrap: nowrap;
    }
  }
  </style>